const express = require('express');
const http = require('http');
const { Server } = require('socket.io');
const cors = require('cors');
const dotenv = require('dotenv');
const connectDB = require('./config/db');
const { initializeDatabase } = require('./config/mysqlConfig');
const userRoutes = require('./routes/userRoutes');
const messageRoutes = require('./routes/messageRoutes');
const groupRoutes = require('./routes/groupRoutes');
const { setupSocketIO } = require('./services/socketService');
const path = require('path');
const fs = require('fs');

// 加载环境变量
dotenv.config();

// 检查关键环境变量
console.log('🔧 环境变量检查:');
console.log('  JWT_SECRET:', process.env.JWT_SECRET ? '已设置' : '❌ 未设置 (将使用默认值)');
console.log('  MONGODB_URI:', process.env.MONGODB_URI || 'mongodb://localhost:27017/litechat (默认)');
console.log('  MYSQL_PASSWORD:', process.env.MYSQL_PASSWORD || '123456 (默认)');
console.log('');

// 连接MongoDB数据库
connectDB();

// 初始化MySQL数据库
initializeDatabase().then(success => {
  if (!success) {
    console.error('MySQL 数据库初始化失败，应用可能无法正常工作');
  }
}).catch(error => {
  console.error('MySQL 数据库初始化出错:', error);
});

const app = express();

// 确保上传目录存在
const uploadsPath = path.join(__dirname, '../uploads');
const avatarsPath = path.join(uploadsPath, 'avatars');

if (!fs.existsSync(uploadsPath)) {
  fs.mkdirSync(uploadsPath, { recursive: true });
  console.log('创建上传根目录:', uploadsPath);
}

if (!fs.existsSync(avatarsPath)) {
  fs.mkdirSync(avatarsPath, { recursive: true });
  console.log('创建头像目录:', avatarsPath);
}

// 中间件
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: false }));

// 静态文件服务 - 用于提供头像和其他上传的文件
app.use('/uploads', express.static(path.join(__dirname, '../uploads')));
console.log('静态文件路径:', path.join(__dirname, '../uploads'));

// 路由
app.use('/api/users', userRoutes);
app.use('/api/messages', messageRoutes);
app.use('/api/groups', groupRoutes);

// 根路由
app.get('/', (req, res) => {
  res.json({ message: '轻语(LiteChat)服务器正在运行' });
});

// 启动服务器
const PORT = process.env.PORT || 5000;

// 直接使用固定端口启动服务器
const startServer = () => {
  const server = http.createServer(app);

  server.listen(PORT, () => {
    console.log(`服务器运行在端口: ${PORT}`);

    // WebSocket服务器配置
    const io = new Server(server, {
      cors: {
        origin: process.env.CLIENT_URL || "http://localhost:3000",
        methods: ["GET", "POST"]
      }
    });

    // 将Socket.IO实例保存到app中，供控制器使用
    app.set('socketio', io);
    
    // 设置Socket.IO服务
    setupSocketIO(io);
  });

  server.on('error', (error) => {
    if (error.code === 'EADDRINUSE') {
      console.error(`错误：端口 ${PORT} 已被占用，请手动更改端口或关闭占用该端口的程序`);
      process.exit(1);
    } else {
      console.error('服务器启动错误:', error);
      process.exit(1);
    }
  });
};

startServer();